import copy
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from MedicineReminder.models import Medicine, ReminderItem
from SecureHelperServer.settings import formatResponseData
from utils.conf import newID, verifyID, Response
from utils.custom import MyJWTAuthentication


class SaveReminder(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]

    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        保存/更新 药品提醒信息
        """
        data = copy.deepcopy(formatResponseData)
        try:
            medicineId = request.data.get("id")
            name = request.data.get("name")
            startDateTimeStamp = request.data.get("startDateTimeStamp")
            endDateTimeStamp = request.data.get("endDateTimeStamp")
            dosage = request.data.get("dosage")
            reminderItemList = request.data.get("reminderItemList")

            if not (name and startDateTimeStamp and endDateTimeStamp and dosage and reminderItemList):
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            # 保存/更新之前数据库中的记录
            oldReminderItemIDList = [i.id for i in
                                     ReminderItem.objects.filter(medicine_id=medicineId, medicine__user=request.user)]

            # 存入药品
            medicineObj = {
                "name": name,
                "startTimeStamp": startDateTimeStamp,
                "endTimeStamp": endDateTimeStamp,
                "dosage": dosage,
                "user": request.user,
            }

            if verifyID(medicineId):
                medicineObj["id"] = medicineId
            else:
                medicineObj["id"] = newID()

            medicine, isCreate = Medicine.objects.update_or_create(defaults=medicineObj, id=medicineObj["id"])

            # 存入提醒
            for obj in reminderItemList:
                reminderItemObj = {"timeStamp": obj["timeStamp"], "medicine": medicine}

                if verifyID(obj["id"]):
                    reminderItemObj["id"] = obj["id"]
                else:
                    reminderItemObj["id"] = newID()

                reminderItem, isCreate = ReminderItem.objects.update_or_create(defaults=reminderItemObj,
                                                                               id=reminderItemObj["id"])
                if not isCreate:
                    oldReminderItemIDList.remove(obj["id"])

            # 删除多余的提醒
            for reminderItemId in oldReminderItemIDList:
                ReminderItem.objects.get(id=reminderItemId).delete()

            return Response(data=data, responseMsg="设置成功",
                            loggerMsg=f"保存/更新 药品提醒信息: 成功，uid={request.user.uid}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
